import axios from 'axios'

// 带cookie请求
axios.defaults.headers.post['Content-Type'] = 'application/json'

const http = axios.create({
  // baseURL: 'http://admin.umayle.com'
  baseURL: `${import.meta.env.VITE_BASE_URL}/api`
})

//  request 请求拦截器 - 请求之前headers加sid
http.interceptors.request.use(
  config => {
    //  每次发送请求之前检测都vuex存有token,那么都要放在请求头发送给服务器
    return config
  },
  err => {
    return err
  }
)
//  response 错误统一处理
http.interceptors.response.use(
  res => {
    return res.data
  },
  err => {
    console.log('接口访问失败')
    return err
  }
)

// 封装请求的api
const callapi = (method = 'GET', url, data = {}) => {
  const params = method === 'GET' ? data : {}
  const body = ['POST', 'PUT', 'PATCH'].includes(method) ? data : {}
  const options = { method, url, params, data: body }
  return http(options)
}

export const upload = (url, file) => {
  return new Promise((resolve, reject) => {
    http
      .post(url, file, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}

// 封装GET请求函数
export const get = (url, data) => callapi('GET', url, data)
export const post = (url, data) => callapi('POST', url, data)
export const put = (url, data) => callapi('PUT', url, data)
export const deleteapi = (url, data) => callapi('DELETE', url, data)
export const patchApi = (url, data) => callapi('PATCH', url, data)
